<template>
  <section class="chart">
    <el-row>
      <el-col class="index-warn" :span="24">
        <h4>性能</h4>
        <el-col :span="12" v-loading="isLoading.chartCpu">
          <div id="chartCpu" class="citem" style=" width:100%; height:200px;"></div>
        </el-col>
        <el-col :span="12" v-loading="isLoading.chartMemory">
          <div id="chartMemory" class="citem" style=" width:100%; height:200px;"></div>
        </el-col>
      </el-col>

      <el-col class="index-warn leftHalf half-warn">
        <h4>HDFS</h4>
        <el-col :span="12" v-loading="isLoading.chartHdfs">
          <div id="chartHdfs" class="citem" style=" width:100%; height:200px;"></div>
        </el-col>
        <el-col :span="12" v-loading="isLoading.dataNodes">
          <div id="chartDataNodes" class="citem" style=" width:100%; height:200px;">
            <h3>DataNodes存活量</h3>
            <div class="camys"> {{dataNodes.started_count}} / {{dataNodes.total_count}}</div>
          </div>
        </el-col>
      </el-col>

      <el-col class="index-warn half-warn">
        <h4>YARN</h4>
        <el-col :span="12" v-loading="isLoading.chartYarn">
          <div id="chartYarn" class="citem" style=" width:100%; height:200px;"></div>
        </el-col>
        <el-col :span="12" v-loading="isLoading.nodeManagers">
          <div id="chartDataManagers" class="citem" style="width:100%; height:200px;">
            <h3>NodeManagers存活量</h3>
            <div class="camys">
              {{nodeManagers.started_count}} / {{nodeManagers.total_count}}
            </div>
          </div>
        </el-col>
      </el-col>

      <el-col class="index-warn leftHalf half-warn">
        <h4>HBASE</h4>
        <el-col :span="10" v-loading="isLoading.chartRegion">
          <div id="chartRegion" class="citem" style="width:100%; height:200px;"></div>
        </el-col>
        <el-col :span="7" v-loading="isLoading.clusterRegions">
          <div id="chartHbase" class="citem" style=" width:100%; height:200px;">
            <h3>HBASE表数量</h3>
            <div class="camys">
              {{habseTables}}
            </div>
          </div>
        </el-col>
        <el-col :span="7" v-loading="isLoading.nodeManagers">
          <div id="chartHbase" class="citem" style=" width:100%; height:200px;">
            <h3>Region数量</h3>
            <div class="camys">
              {{clusterRegions}}
            </div>
          </div>
        </el-col>
      </el-col>

      <el-col class="index-warn half-warn">
        <h4>HIVE</h4>
        <el-col :span="8" v-loading="isLoading.hiveDBs">
          <div id="chartBase" class="citem" style=" width:100%; height:200px;">
            <h3>DataBase数量</h3>
            <div class="camys">
              {{hiveDBs}}

            </div>
          </div>
        </el-col>
        <el-col :span="8" v-loading="isLoading.hiveTables">
          <div id="chartHive" class="citem" style=" width:100%; height:200px;">
            <h3>HIVE表数量</h3>
            <div class="camys">
              {{hiveTables}}

            </div>
          </div>
        </el-col>

        <el-col :span="8" v-loading="isLoading.hivePartitions">
          <div id="chartHbase" class="citem" style=" width:100%; height:200px;">
            <h3>HIVE分区数量</h3>
            <div class="camys">
              {{hivePartitions}}
            </div>
          </div>
        </el-col>
      </el-col>
    </el-row>
  </section>
</template>

<script>
  import util from '../../common/util'
  import dao from '../../common/dao'
  import echarts from 'echarts'
  
  export default {
    components: {},
    props: ['refreshRate', 'dateValue', 'rTime','reSizeCode'],
    data() {
      return {
        chartCpu: null,
        chartMemory: null,
        chartHdfs: null,
        chartDataNodes: null,
        chartYarn: null,
        chartRegion: null,
        dataNodes: {
          started_count: "0",
          total_count: "0"
        },
        nodeManagers: {
          started_count: "0",
          total_count: "0"
        },
        habseTables: "0",
        clusterRegions: "0",
        hiveDBs: "0",
        hiveTables: "0",
        hivePartitions: "0",
        isLoading: {
          chartCpu: false,
          chartMemory: false,
          chartHdfs: false,
          dataNodes: false,
          chartYarn: false,
          nodeManagers: false,
          chartRegion: false,
          habseTables: false,
          clusterRegions: false,
          hiveDBs: false,
          hiveTables: false,
          hivePartitions: false,
        }
      }
    },
    watch: { //刷新频率
      refreshRate(){
        // this.poll();
      },
      reSizeCode(n,o){
        window.onresize = this.resizeAllChart
      this.resizeAllChart()
      }
    },
    methods: {
      bChartCpu(timer, idleData, niceData, systemData, userData){ //CPU使用率
        let xAxisData = timer || [];
        let idle = idleData || [];
        let nice = niceData || [];
        let user = userData || [];
        let system = systemData || [];

        let option = {
          title: {
            text: 'CPU使用率',
          },
          tooltip: {
            trigger: 'axis',
          //  formatter: "{b}<br>{a}:{c}% <br>{a1}:{c1}% <br>{a2}:{c2}% <br>{a3}:{c3}%"
          },
          legend: {
            data: ['Idle', 'User', 'System', 'Nice'],
            bottom: '0'
          },
          grid: {
            left: 35,
            bottom: 43,
          },
          xAxis: {
            name: '',
            type: 'category',
            boundaryGap: false,
            data: xAxisData,
            axisLine: {
              show: true
            },
            axisLabel: {
              formatter: function (value, index) {
                // 格式化成月/日，只在第一个刻度显示年份
                var date = new Date(value);
                var texts = [(date.getMonth() + 1), date.getDate()];
               /* if (index === 0) {
                 texts.unshift(date.getYear());
               } */
                return texts.join('/');
              }
            }
          },
          yAxis: {
            name: '%',
            max: 100,
            splitLine: {
              show: true
            }
          },
          series: [{
            name: 'Idle',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: idle,
          }, {
            name: 'User',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: user,
            animationDelay: function (idx) {
            //  return idx * 10 + 100;
            }
          }, {
            name: 'System',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: system,
            animationDelay: function (idx) {
            //  return idx * 10 + 100;
            }
          }, {
            name: 'Nice',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: nice,
            animationDelay: function (idx) {
            //  return idx * 10 + 100;
            }
          }],
          animationEasing: 'elasticOut',
          animationDelayUpdate: function (idx) {
          //  return idx * 5;
          }
        };
        this.chartCpu = echarts.init(document.getElementById('chartCpu'));
        this.chartCpu.setOption(option);
      },
      bChartMemory(timer, useData, totalData, swapData, shareData, cacheData, bufferData){ //内存使用率

        let xAxisData = timer || [];
        let use = useData || [];
        let total = totalData || [];
        let swap = swapData || [];
        let share = shareData || [];
        let cache = cacheData || [];
        let buffer = bufferData || [];

        let option = {
          title: {
            text: '内存使用量',
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['Use', 'Total', 'Swap', 'Share', 'Cache', 'Buffer'],
            bottom: '0'
          },
          grid: {
            left: 45,
            bottom: 43
          },
          xAxis: {
            name: '',
            type: 'category',
            boundaryGap: false,
            data: xAxisData,
            axisLabel: {
              formatter: function (value, index) {
                // 格式化成月/日，只在第一个刻度显示年份
                var date = new Date(value);
                var texts = [(date.getMonth() + 1), date.getDate()];
              /*  if (index === 0) {
                 texts.unshift(date.getYear());
               } */
                return texts.join('/');
              }
            }
          },
          yAxis: {
            name: 'GB',
            splitLine: {
              show: false
            }
          },
          series: [{
            name: 'Use',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: use,
            animationDelay: function (idx) {
              return idx * 10;
            }
          }, {
            name: 'Total',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: total,
            animationDelay: function (idx) {
              return idx * 10 + 100;
            }
          }, {
            name: 'Swap',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: swap,
            animationDelay: function (idx) {
              return idx * 10 + 100;
            }
          }, {
            name: 'Share',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: share,
            animationDelay: function (idx) {
              return idx * 10 + 100;
            }
          }, {
            name: 'Cache',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: cache,
            animationDelay: function (idx) {
              return idx * 10 + 100;
            }
          }, {
            name: 'Buffer',
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: buffer,
            animationDelay: function (idx) {
              return idx * 10 + 100;
            }
          }],
          animationEasing: 'elasticOut',
          animationDelayUpdate: function (idx) {
            return idx * 5;
          }
        };
        this.chartMemory = echarts.init(document.getElementById('chartMemory'));
        window.onresize = this.chartMemory.resize;
        this.chartMemory.setOption(option);

      },
      bChartHdfs(y = 0, y1 = 1){
        this.chartHdfs = echarts.init(document.getElementById('chartHdfs'));
        window.onresize = this.chartHdfs.resize;
        let opt = {
          title: {
            text: 'HDFS磁盘使用量',
          },
          tooltip: {
            trigger: 'item',
            formatter: "{a}<br> {b}: {c} ({d}%)",
            position: ['45%', '65%']
          },
          legend: {
            show: false,
            orient: 'vertical',
            left: 'left',
            top: '20',
            data: ['HDFS', '空闲']
          },
          series: [
            {
              name: 'HDFS磁盘使用量',
              type: 'pie',
              radius: ['45%', '60%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  textStyle: {
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: [
                {value: y, name: 'HDFS'},
                {value: y1, name: '空闲'},
              ]
            }
          ]
        }
      
        this.chartHdfs.setOption(opt);
      },
      bChartYarn(y = 0, y1 = 1){
        this.chartYarn = echarts.init(document.getElementById('chartYarn'));
        this.chartYarn.setOption({
          title: {
            text: 'YARN内存',

          },
          tooltip: {
            trigger: 'item',
            formatter: "{a}<br> {b}: {c} ({d}%)",
            position: ['45%', '65%']
          },
          legend: {
            show: false,
            left: 'left',
            top: '20',
            orient: 'vertical',
            data: ['YARN', '空闲']
          },
          series: [
            {
              name: '访问来源',
              type: 'pie',
              radius: ['45%', '60%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  textStyle: {
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: [
                {value: y, name: 'YARN'},
                {value: y1, name: '空闲'},
              ]
            }
          ]
        });
      },
      bChartRegion(y = 0, y1 = 1){
        let option = {
          title: {
            text: 'RegionServer 数量',
          },
          tooltip: {
            trigger: 'item',
            formatter: "{a}<br> {b}: {c} ({d}%)",
            position: ['35%', '65%']
          },
          legend: {
            show: false,
            left: 'left',
            bottom: 0,
            data: ['Dead', 'Live']
          },
          series: [
            {
              name: 'RegionServer 数量',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  show: true,
                  textStyle: {
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: [
                {value: y, name: 'Dead'},
                {value: y1, name: 'Live'},
              ]
            }
          ]
        };
        this.chartRegion = echarts.init(document.getElementById('chartRegion'));
        this.chartRegion.setOption(option);
      },
      /* 获取数据 */
      getCPUUsageHttp () { //CPU性能请求

        let arg = {
          "metricNames": "?fields=metrics/cpu/Nice._avg[start_time,end_time,15],metrics/cpu/System._avg[start_time,end_time,15],metrics/cpu/User._avg[start_time,end_time,15],metrics/cpu/Idle._avg[start_time,end_time,15]",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };

        dao.getCPUUsage(arg).then((response) => { //success
          if (this.$route.name !== '平台监控') {
            return false
          }
          if (!response.body.data) {
            return false
          }
          let [timer, idleData, niceData, systemData, userData] = [[], [], [], [], []];
          let resParm = JSON.parse(response.body.data) || {};

          let idle = resParm.Idle_avg || {};
          let nice = resParm.Nice_avg || {};
          let system = resParm.System_avg || {};
          let user = resParm.User_avg || {};

          for (let i = 0; i < idle.length; i++) {
            let tmp = idle[i] || [];
            idleData.push((tmp[0] || 0).toFixed(2));
          }
          for (let i = 0; i < nice.length; i++) {
            let tmp = nice[i] || [];
            niceData.push((tmp[0] || 0).toFixed(2));
          }
          for (let i = 0; i < system.length; i++) {
            let tmp = system[i] || [];
            systemData.push((tmp[0] || 0).toFixed(2));
          }
          for (let i = 0; i < user.length; i++) {
            let tmp = user[i] || [];
            userData.push((tmp[0] || 0).toFixed(2));
          }

          if (idle.length) {
            for (let i = 0; i < idle.length; i++) {
              let tmp = user[i] || [];
              timer.push(util.pokeToTime(tmp[1] || 0));
            }
          } else if (nice.length) {

          } else if (system.length) {

          } else if (system.length) {

          } else {
            x = 0;
          }
          this.bChartCpu(timer, idleData, niceData, systemData, userData);
        })

      },
      getMemoryUsageMemsHttp () { //内存使用请求

        let arg = {
          "metricNames": "?fields=metrics/memory/Buffer._avg[start_time,end_time,15],metrics/memory/Cache._avg[start_time,end_time,15],metrics/memory/Share._avg[start_time,end_time,15],metrics/memory/Swap._avg[start_time,end_time,15],metrics/memory/Total._avg[start_time,end_time,15],metrics/memory/Use._avg[start_time,end_time,15]",
          "starttime": this.rTime[0],//开始时间戳
          "endtime": this.rTime[1]//结束时间戳
        };
        dao.getMemoryUsage(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          ;
          if (!response.body.data) {
            return false
          }
          ;
          let rParam = response.body.data || {};
          let [timer, useData, totalData, swapData, shareData, cacheData, bufferData] = [[], [], [], [], [], [], []];

          let resParm = JSON.parse(response.body.data);

          let use = resParm.Use_avg || {};
          let total = resParm.Total_avg || {};
          let swap = resParm.Swap_avg || {};
          let share = resParm.Share_avg || {};
          let cache = resParm.Cache_avg || {};
          let buffer = resParm.buffer_avg || {};

          for (let i = 0; i < use.length; i++) {
            let tmp = use[i] || 0;
            useData.push(( (tmp[0] || 0) / 1024 ).toFixed(2));
          }
          for (let i = 0; i < total.length; i++) {
            let tmp = total[i] || 0;
            totalData.push(( (tmp[0] || 0) / 1024 ).toFixed(2));
          }
          for (let i = 0; i < swap.length; i++) {
            let tmp = swap[i] || [];
            swapData.push(( (tmp[0] || 0) / 1024 ).toFixed(2));
          }
          for (let i = 0; i < share.length; i++) {
            let tmp = share[i] || [];
            shareData.push(( (tmp[0] || 0) / 1024 ).toFixed(2));
          }
          for (let i = 0; i < cache.length; i++) {
            let tmp = share[i] || [];
            cacheData.push(( (tmp[0] || 0) / 1024 ).toFixed(2));
          }
          for (let i = 0; i < buffer.length; i++) {
            let tmp = buffer[i] || [];
            bufferData.push(( (tmp[0] || 0) / 1024 ).toFixed(2));
          }

        //  获取时间
          if (use.length) {
            for (let i = 0; i < use.length; i++) {
              let tmp = use[i] || [];
              timer.push(util.pokeToTime(tmp[1] || 0));
            }
          } else {
            x = 0;
          }
          this.bChartMemory(timer, useData, totalData, swapData, shareData, cacheData, bufferData);
        })

      },
      getHdfsCapacityHttp () { //HDFS磁盘使用量 饼图
        let arg = {
          "metricNames": "/components/NAMENODE",
          "app_id": "namenode",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };

        dao.getHdfsCapacity(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          let resParm = response.body || [];
          let y = resParm.y || [];
          let y1 = resParm.y_0 || [];
          this.bChartHdfs(y, y1);
        });

      },
      getDataNodesHttp () { //DataNodes存活量

        let arg = {
          "metricNames": "/components/DATANODE",
          "app_id": "DATANODE",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getDataNodes(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          ;
          let resParm = response.body;
          this.dataNodes.started_count = resParm.y || '';
          this.dataNodes.total_count = resParm.y_0 || '';
        });

      },
      getYARNMemoryHttp () { //YARN 内存使用 请求
        let arg = {
          "metricNames": "/components/RESOURCEMANAGER",
          "app_id": "namenode",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };

        dao.getYARNMemory(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          ;
          let resParm = response.body;
          let y = resParm.y || [];
          let y1 = resParm.y_0 || [];
          this.bChartYarn(y, y1);
        });
      },
      getNodeManagersHttp () { //YARN Node Manger存活量 请求

        let arg = {
          "metricNames": "/components/NODEMANAGER",
          "app_id": "namenode",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getNodeManagers(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          let resParm = response.body || [];
          this.nodeManagers.started_count = resParm.y || '';
          this.nodeManagers.total_count = resParm.y_0 || '';
        });

      },
      getOnlineRegionServerHttp () { //RegionServer数量 请求

        let arg = {
          "metricNames": "/components/HBASE_REGIONSERVER",
          "type": "Ambari",
          "app_id": "hbase",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getOnlineRegionServer(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          let resParm = response.body || [];
          let y = resParm.y || [];
          let y1 = resParm.y_0 || [];
          this.bChartRegion(y1, y);
        })

      },
      getHbaseTablesHttp () { //HDFS表数量 请求

        let arg = {
          "app_id": "hbase",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getHbaseTables(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          this.habseTables = response.body.data || 0;
        })

      },
      getClusterRegionsHttp () { //HDFS region数量 请求

        let arg = {
          "metricNames": "regionserver.Server.regionCount._sum",
          "type": "Ambari",
          "app_id": "hbase",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getClusterRegions(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }

          if (response.body) {
            let resParm = response.body || {};
            if (!resParm.results || !resParm.results[0]) {
              return false
            }
            let yIndex = resParm.results[0].y.length - 1 || [];
            this.clusterRegions = resParm.results[0].y[yIndex] || [];
          }
        })

      },
      getHiveDBsHttp () { //HIVE Database表数量 请求

        let arg = {
          "metricNames": "default.General.init_total_count_dbs._max",
          "type": "Ambari",
          "app_id": "hivemetastore",
          "starttime": this.rTime[0],//开始时间戳
          "endtime": this.rTime[1]//结束时间戳
        };
        dao.getHiveDBs(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          if (response.body) {
            let resParm = response.body;
            if (!resParm.results || !resParm.results[0]) {
              return false
            }
            let yIndex = resParm.results[0].y.length - 1 || [];
            this.hiveDBs = resParm.results[0].y[yIndex] || [];
          }
        })
      },
      getHiveTablesHttp () { //HIVE 表数量 请求

        let arg = {
          "metricNames": "default.General.init_total_count_tables._max",
          "type": "Ambari",
          "app_id": "hivemetastore",
          "starttime": this.rTime[0],
          "endtime": this.rTime[1]
        };
        dao.getHiveTables(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          if (response.body) {
            let resParm = response.body;
            if (!resParm.results || !resParm.results[0]) {
              return false
            }
            let yIndex = resParm.results[0].y.length - 1 || [];
            this.hiveTables = resParm.results[0].y[yIndex] || 0;
          }
        })

      },
      getHivePartitionsHttp () { //HIVE 分区数量 请求

        let arg = {
          "metricNames": "default.General.init_total_count_tables._max",
          "type": "Ambari",
          "app_id": "hivemetastore",
          "starttime": this.rTime[0],//开始时间戳
          "endtime": this.rTime[1]//结束时间戳
        };
        dao.getHivePartitions(arg).then((response) => {
          if (this.$route.name !== '平台监控') {
            return false
          }
          if (response.body) {
            let resParm = response.body;
            if (!resParm.results || !resParm.results[0]) {
              return false
            }
            let yIndex = resParm.results[0].y.length - 1;
            this.hivePartitions = (resParm.results || [])[0].y[yIndex];
          }
        }, (response) => {
          console.log(response);
        })
      },
      resizeAllChart(){
        this.chartCpu.resize()
        this.chartMemory.resize()
        this.chartHdfs.resize()
        this.chartYarn.resize()
        this.chartRegion.resize()
      }
    },
    mounted () {
      this.bChartCpu()
      this.bChartMemory()
      this.bChartHdfs()
      this.bChartYarn()
      this.bChartRegion()

      this.$nextTick(() => {
        window.onresize = this.resizeAllChart

        this.getCPUUsageHttp();
        this.getMemoryUsageMemsHttp();

        this.getHdfsCapacityHttp();
        this.getDataNodesHttp();

        this.getYARNMemoryHttp();
        this.getNodeManagersHttp();

        this.getOnlineRegionServerHttp();
        this.getHbaseTablesHttp();
        this.getClusterRegionsHttp();

        this.getHiveDBsHttp();
        this.getHiveTablesHttp();
        this.getHivePartitionsHttp();
      });

    },
  }
</script>

<style scoped>
  body {
    box-sizing: border-box;
  }

  .half-warn {
    width: 49%;
  }

  .leftHalf {
    margin-right: 2%;
  }

  .index-warn {
    padding: 10px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
  }

  .citem {
    padding: 10px;
    margin-right: 15px;
  }

  .citem h3 {
    margin: 0;
    text-align: center;
  }

  .chart {
    width: 100%;
    float: left;
  }

  h4 {
    color: #999;
  }

  .camys {
    width: 100%;
    text-align: center;
    font-size: 35px;
    line-height: 179px;
    color: #1d90e6;
  }
</style>